require 'time'
require 'watir-webdriver'

class RequestFinder

  def initialize(navigator)
    @navigator = navigator
  end

  def get_request_ids_for_users(users, options={})
    b = Watir::Browser.new
    requests = users.map { |user| get_requests_for_user user, b }.flatten
    b.close
    start_date = options[:start_date]
    requests.reject! { |r| start_date > r[:submitted_on] } if start_date
    requests.map { |r| r[:id] }.sort
  end

  private

  def get_requests_for_user(user, b)
    login_command = LoginCommand.new user[:username], user[:password], @navigator
    login_command.execute b
    @navigator.goto 'hd/ticket/euTicketFind.ssp', b
    get_all_requests b
  end

  def get_all_requests(b)
    b.button(value: 'Find').click
    rows = b.tables[1].rows.to_a
    rows.shift 2

    requests = rows.map do |row|
      cells = row.cells.to_a
      next if cells.empty?
      {
          id: cells[0].text.to_i,
          submitted_on: Time.parse(cells[2].text)
      }
    end

    requests.compact
  end

end

